import _ from 'lodash';
import { firewallRequest } from '@core/utils/request';

export interface IpsRuleFirewallSummary {
  nameCn: string,
  nameEn: string,
  children?: Array<IpsRuleFirewallSummary>,
}

export const IpsRuleType = {
  Method: 'method',
  Target: 'target',
};

export default class Ips {
  private static _listOfMethod: Array<IpsRuleFirewallSummary> = [];

  static fetchSummaryList = (params: { type: string }) => {
    return firewallRequest.get<
      { type: string },
      Array<IpsRuleFirewallSummary>
    >('/ctcloud/vfw/v1_ips_rule_type', { params });
  };

  static getMethodSummaryList = async () => {
    if (_.isEmpty(Ips._listOfMethod)) {
      Ips._listOfMethod = await Ips.fetchSummaryList({ type: IpsRuleType.Method });
    }
    return Ips._listOfMethod;
  };

  static getMethodByName = (parentName: string, childName?: string) => {
    const parentMethod = Ips._listOfMethod.find((method) => (
      method.nameEn === parentName || method.nameCn === parentName
    ));
    const childMethod = parentMethod?.children?.find((method) => (
      method.nameEn === childName || method.nameCn === parentName
    ));
    return { parent: parentMethod, child: childMethod };
  };
}
